package it.univaq.mwt.tp;

import it.univaq.mwt.tp.Item;

import java.io.Serializable;

import javax.persistence.*;

import static javax.persistence.GenerationType.AUTO;
import static javax.persistence.CascadeType.PERSIST;
import static javax.persistence.CascadeType.REFRESH;
import static javax.persistence.AccessType.FIELD;

/**
 * Entity implementation class for Entity: OrderLine
 * 
 */
@Entity
@Access(FIELD)
public class OrderLine implements Serializable {
	@Id
	@GeneratedValue(strategy = AUTO)
	private int oliID;
	private int quantity;
	@ManyToOne(cascade = { PERSIST, REFRESH })
	private Item item;
	private static final long serialVersionUID = 1L;

	public OrderLine() {
		super();
	}

	public OrderLine(Item item) {
		this.item = item;
	}

	
	public int getOliID() {
		return this.oliID;
	}

	public void setOliID(int oliID) {
		this.oliID = oliID;
	}

	public int getQuantity() {
		return this.quantity;
	}

	public void setQuantity(int quantity) throws Exception {
		if (item.getStock() >= quantity) {
			item.setStock(item.getStock() - quantity);
			this.quantity = quantity;
		} else {
			throw new Exception("Quantity not available.");
		}
	}

	
	public Item getItem() {
		return this.item;
	}

	public void setItem(Item item) {
		this.item = item;
	}

	@Transient
	public float getLineTotal() {
		return (float)quantity*item.getPrice();
	}
}
